package com.tanhua.dubbo.api.db;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.QuizReport;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.SimilarUser;
import com.tanhua.dubbo.mapper.QuizReportMapper;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

import com.tanhua.domain.db.QuizStar;
import com.tanhua.domain.db.QuizTemplate;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.transaction.annotation.Transactional;


/**
 * @Author Administrator
 * @Date 2021/8/24  20:15
 */
@Service
@Slf4j
@Transactional
public class QuizReportApiImpl implements QuizReportApi {

    @Autowired
    private QuizReportMapper quizReportMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private QuizStarApi quizStarApi;

    @Reference
    private QuizTemplateApi quizTemplateApi;

    /**
     * 根据用户id和问卷id查询最新报告id
     *
     * @param userId
     * @return
     */
    @Override
    public Integer queryReportId(Long userId, Integer bookId) {

        QueryWrapper<QuizReport> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("book_id", bookId);
        QuizReport quizReport = quizReportMapper.selectOne(wrapper);

        if (quizReport == null) {
            return null;
        }
        return quizReport.getReportId();
    }


    /**
     * 根据报告id查询结果
     *
     * @param reportId
     * @return
     */
    @Override
    public QuizReport queryReportById(Integer reportId) {
        return quizReportMapper.selectById(reportId);
    }

    /**
     * 根据分数查询临近几条用户记录
     *
     * @param userId
     * @param score
     * @param i
     * @return
     */
    @Override
    public Integer[] queryRangeUserReport(Integer userId, Integer score, int i) {
        return quizReportMapper.queryRangeUserReport(userId, score, i);
    }

    /**
     * 根据用户id，查询用户集合
     *
     * @param userIds
     * @return
     */
    @Override
    public List<SimilarUser> querySimilarUsers(Integer[] userIds) {
        List<SimilarUser> similarUsers = null;
        if (userIds.length != 0) {
            similarUsers = new ArrayList<SimilarUser>();
            for (Integer userId : userIds) {
                SimilarUser similarUser = new SimilarUser();
                similarUser.setId(userId);
                UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().lambda().eq(UserInfo::getId, userId));
                similarUser.setAvatar(userInfo.getAvatar());
                similarUsers.add(similarUser);
            }
        }
        return similarUsers;

    }

    /**
     * 根据分数查询结果表的到对应分数的记录
     *
     * @param score
     * @return
     */
    @Override
    public Integer queryQuizReport(int score, Long userId, int bookId) {
        //用户id
        int currentId = Integer.parseInt(userId.toString());
        //1.根据分数区间查询模板表
        QuizTemplate quizTemplate = quizTemplateApi.qrueyTemplateByscore(score);
        Integer templateId = quizTemplate.getTemplateId();//模板id
        //2.查询星级表
        QuizStar quizStar = quizStarApi.queryStarById(userId);
        //3判断星级表是否存在该用户的星级记录
        if (quizStar == null) {
            //3.1插入星级记录
            QuizStar myQuizStar = new QuizStar();
            myQuizStar.setTemplateId(templateId);
            myQuizStar.setUserId(currentId);
            myQuizStar.setUserStar(2);
            quizStarApi.saveQuizStar(myQuizStar);
        }
        //3.2如果星级表中的模板id的不相同,则更新星级记录
        if (quizStar != null) {
            quizStar.setTemplateId(templateId);
            //3.3如果分数大于20就把星级加1
            if (score >= 20) {
                Integer userStar = quizStar.getUserStar();
                quizStar.setUserStar(++userStar);
            }
            //更新星级记录
            quizStarApi.updateQuizStar(quizStar);
        }
        //4.根据userId和bookid查询结果表，如果有记录则更新，如果没有就新增
        QueryWrapper<QuizReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", currentId).eq("book_id", bookId);
        QuizReport quizReport = quizReportMapper.selectOne(queryWrapper);
        //4.1如果为null则插入数据
        if (quizReport == null) {
            //4.2更改结果对象属性
            quizReport = setQuizReport(score, currentId, quizTemplate,bookId);
            //4.3插入到结果表
            quizReportMapper.insert(quizReport);
        } else {
            //4.2更改结果对象属性
            BeanUtils.copyProperties(quizTemplate,quizReport);
            quizReport.setScore(score);
            quizReportMapper.updateById(quizReport);
        }
        return quizReport.getReportId();
    }

    /**
     * 更新结果对象
     *
     * @param score
     * @param userId
     * @param quizTemplate
     */
    public QuizReport setQuizReport(int score, int userId, QuizTemplate quizTemplate,Integer bookId) {
        QuizReport qr = new QuizReport();
        qr.setUserId(userId);//当前用户id
        qr.setBookId(bookId);//设置问卷类型
        qr.setConclusion(quizTemplate.getConclusion()); //结果总结
        qr.setDimensions(quizTemplate.getDimensions());//维度
        qr.setReportCover(" https://tanhua-dev.oss-cn-zhangjiakou." +
                "aliyuncs.com/images/test_soul/owl.png");//封面
        qr.setScore(score);//分数
        return qr;
    }
}
